from PyQt5.QtCore import QUrl, QObject, pyqtSlot
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine, qmlRegisterType
import os,shutil

class Func(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.input_folder_name = ''
        self.output_fi_name = ''
        #self.input_fc_name = ''
        self.output_folder_name = ''
        self.input_list = []
        self.input_list_num = 0
        self.output_list = []
        self.output_fp = None
        self.number = 0
        
    @pyqtSlot(str)#
    def list_file(self, folder_name):
        self.input_folder_name = folder_name
        self.input_list = os.listdir(self.input_folder_name)
        self.input_list_num = len(self.input_list)
        #self.input_fc_name = self.input_folder_name+'/fc'
        #print(self.input_list)
        #return true
        
    @pyqtSlot(str)
    def list_folder(self, folder_name):
        self.output_folder_name = folder_name
        self.output_list = os.listdir(self.output_folder_name)
        self.output_fi_name = self.output_folder_name+'/fi'
        self.output_list.remove('fi')
        #print(self.output_list)
    @pyqtSlot(result=str)
    def load(self):
        if not os.path.exists(self.output_fi_name):
            os.mkdir(self.output_fi_name)
        self.output_fp = open(self.output_fi_name+'/output.txt', 'a')
        ret = ''
        for line in self.output_list:
            ret += line + ":"
        return ret[:-1]
    
    @pyqtSlot(str,str)
    def output(self,file_name,type_name):
        self.output_fp.write(file_name+','+type_name+"\n")
        
    @pyqtSlot(result=str)
    def next(self):
        if(os.path.exists(self.input_folder_name + '/' +\
                    self.input_list[self.number])):
            shutil.move(self.input_folder_name + '/' +\
                    self.input_list[self.number],self.output_fi_name)
        self.number += 1
        if self.number >= self.input_list_num:
            return ""
        return self.input_list[self.number]
    
    @pyqtSlot(result=str)
    def before(self):
        if self.number <= 0:
            self.number = 0
        else:
            self.number -= 1
        return self.input_list[self.number]

    @pyqtSlot(result=str)
    def save(self):
        self.output_fp.close()
        self.output_fp = open(self.output_fi_name+'/output.txt', 'a')
        

if __name__ == '__main__':  
    path = 'main.qml'
    app = QGuiApplication([])
    qmlRegisterType(Func, "wsn.func", 1, 1, "Func")
    engine = QQmlApplicationEngine()
    rootObject = engine.load(path)
    app.exec_()
